package com.telecom.sxint.app.core.service.Chatservice;

import com.alibaba.fastjson2.JSONObject;
import com.telecom.sxint.app.core.Constant.ChatConstants;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

@Component
public class ChatApi2 {

    private final WebClient webClient;

    public ChatApi2() {
        webClient = WebClient.builder()
                .baseUrl(ChatConstants.baseUrl)
                .defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader("Authorization", "Bearer " + ChatConstants.bearerToken)
                .build();
    }

    public Flux<String> runConversation(String conversationId, String query) {
        String apiUri = "/v2/app/conversation/runs";
        JSONObject params = new JSONObject();
        params.put("app_id", ChatConstants.appId);
        params.put("query", query);
        params.put("stream", true);
        params.put("conversation_id", conversationId);
        return webClient.post().uri(apiUri)
                .bodyValue(params).retrieve().bodyToFlux(String.class)
                .map(this::getCleanAnswer);
    }

    private String getCleanAnswer(String chatResponse) {
        String pattern = "\\^(\\[\\d+])+\\^?";
        return chatResponse.replaceAll(pattern, "").replaceAll("\\*\\*", "");
    }

    public static void main(String[] args) {
    }
}
